<template>
  <div class="mt-1">
    <h4 style="margin: 0 0 0.4rem 1rem; color: gray">
      当前产区:{{ this.$store.getters.productionLine }}
    </h4>
    <van-form>
      <van-field
        v-model="code"
        clearable
        ref="pmfocus"
        @focus="stopKeyborad"
        label="拍码"
        placeholder="请输入拍码"
      />

      <van-row type="flex">
        <van-col span="7"
          ><van-button
            round
            :type="buttoncolortobe"
            size="small"
            style="margin: 1rem 0 0 0.4rem"
            @click="toBeReceived"
            >待收货确认:{{ this.rowDataToBe.length }}</van-button
          ></van-col
        >
        <van-col span="7"
          ><van-button
            round
            :type="buttoncolor"
            size="small"
            style="margin: 1rem 0 0 0.2rem"
            @click="haveReceived"
            >当班已确认:{{ this.rowDataHad.length }}</van-button
          ></van-col
        >
      </van-row>

      <div v-if="this.flag == 'will'">
        <ag-grid-vue
          style="width: 100%; height: 60vh"
          class="ag-theme-alpine mt-1"
          :columnDefs="columnDefsToBe"
          :defaultColDef="defaultColDef"
          :gridOptions="gridOptions"
          :singleClickEdit="true"
          rowSelection="multiple"
          :rowMultiSelectWithClick="true"
          :rowData="rowDataToBe"
        >
        </ag-grid-vue>
      </div>
      <div v-else-if="this.flag == 'had'">
        <ag-grid-vue
          style="width: 100%; height: 55vh"
          class="ag-theme-alpine mt-1"
          :columnDefs="columnDefs"
          :defaultColDef="defaultColDef"
          :gridOptions="gridOptions"
          :singleClickEdit="true"
          rowSelection="multiple"
          :rowMultiSelectWithClick="true"
          :rowData="rowDataHad"
        >
        </ag-grid-vue>
      </div>
      <div v-else-if="this.flag == 'doing'">
        <ag-grid-vue
          style="width: 100%; height: 55vh"
          class="ag-theme-alpine mt-1"
          :columnDefs="columnDefs"
          :defaultColDef="defaultColDef"
          :gridOptions="gridOptions"
          :singleClickEdit="true"
          rowSelection="multiple"
          :rowMultiSelectWithClick="true"
          :rowData="rowData"
        >
        </ag-grid-vue>
      </div>

      <van-row type="flex" justify="space-around">
        <van-col span="7"
          ><van-button block type="info" class="mt-1" @click="getInStorageSX"
            >刷新</van-button
          ></van-col
        >
        <van-col span="7"
          ><van-button
            block
            type="info"
            class="mt-1"
            @click="handleSubmit"
            :v-focus="focus"
            >提交</van-button
          ></van-col
        >
      </van-row>
      <audio src="../../assets/warning.mp3" preload="auto" id="bgMusic"></audio>
    </van-form>
  </div>
</template>

<script>
import { deliveryPlants } from "../../assets/keyValue";
import { AgGridVue } from "ag-grid-vue";
import { CODE_LENGTH } from "../../config";
import { toast, parseQRCode } from "../../utils/common";
import { confirmSubmit, GetInStorageSure } from "../../api/material";

export default {
  name: "ReceiptConfirmation",
  components: { AgGridVue },
  data() {
    return {
      labelWidth: "7em",
      deliveryPlants: deliveryPlants,
      deliveryPlant: "",
      deliveryPlantAndWarehouse: [],
      fieldValue: "",
      deliveryPlantVisible: false,
      submitSure: true,
      focus: false,
      flag: "doing",
      buttoncolor: "default",
      buttoncolortobe: "default",
      code: "",
      TT: "",
      fieldNames: {
        text: "name",
        value: "id",
      },
      gridOptions: {},
      gridApi: null,
      defaultColDef: {
        resizable: true,
      },
      columnDefs: [
        { headerName: "物料", field: "materialCode", width: 90 },
        { headerName: "物料名称", field: "palletName", width: 125 },
        { headerName: "生产日期", field: "prodDate", width: 105 },
        { headerName: "数量", field: "quantity", width: 76, editable: true },
      ],
      columnDefsToBe: [
        { headerName: "物料号", field: "ProductId", width: 90 },
        { headerName: "物料名称", field: "UniqueName", width: 125 },
        { headerName: "生产日期", field: "ProductionDate", width: 105 },
        {
          headerName: "数量",
          field: "Num",
          width: 76,
        },
      ],
      rowData: [],
      rowDataToBe: [],
      rowDataHad: [],
      rowPallenNo: [],
      PallentToBe: [],
      AToBeData: "",
      selectedIds: new Set(),
    };
  },
  watch: {
    //监听拍码，截取数据
    code(val) {
      if (val.length > CODE_LENGTH) {
        let res = parseQRCode(val);
        if (res) {
          this.flag = "doing";
          this.buttoncolortobe = "default";
          this.buttoncolor = "default";
          this.getPallentToBe();
          let Ware = this.PallentToBe.includes(res.palletNo);
          console.log(Ware);
          if (Ware == true) {
            console.log(res);
            this.getAToBeData(res.palletNo, res);
            res.palletName = this.AToBeData;
            this.AToBeData = "";
            this.addItem(res);
            //给待收货减去
            this.deleteData(res.palletNo);
            this.PallentToBe = [];
          } else {
            this.playMusic();
            console.log("1");
            toast("此拍码不是待确认拍码");
            setTimeout(() => {
              this.getInStorageSX();
            }, 4000);
            console.log("2");
            //this.getInStorageSX();
          }
        } else {
          this.playMusic();
          toast("无法识别");
        }
      }
      this.code = "";
      this.TT == "";
      this.$refs.pmfocus.focus();
    },
    //监听按键状态
    flag(val) {
      this.flag = val;
    },
    //监听颜色
    buttoncolor(val) {
      this.buttoncolor = val;
    },
    buttoncolortobe(val) {
      this.buttoncolortobe = val;
    },
  },
  methods: {
    // 消除获取焦点时自动弹出键盘
    stopKeyborad() {
      this.$refs.pmfocus.$refs.input.setAttribute("readonly", "readonly");
      setTimeout(() => {
        this.$refs.pmfocus.$refs.input.removeAttribute("readonly");
      }, 200);
    },
    //播放警示音
    playMusic() {
      setTimeout(() => {
        let audio = document.getElementById("bgMusic");
        audio.play();
      }, 200);
    },
    //拍码录入到表格
    addItem(item) {
      if (!this.rowData.find((it) => it.palletNo === item.palletNo)) {
        this.rowData.push(item);
      } else {
        this.playMusic();
        toast("此拍已被录入");
      }
    },
    //判断数据
    adjustNumber(value) {
      if (value.indexOf(".") != -1) {
        if ((value.split(".")[1] + "").substring(2) * 1 > 0) {
          let newvaluesave = value.substring(0, value.indexOf(".") + 3);
          return newvaluesave;
        } else {
          let newvalue = value.substring(0, value.indexOf("."));
          return newvalue;
        }
      }
    },
    //提交
    async handleSubmit() {
      if (this.flag == "doing") {
        if (this.rowData.length > 0) {
          let user = this.$store.getters.user;
          let id = this.$store.getters.WarehouseId;
          this.findPalletNo();
          let rowPallenNoJoin = this.rowPallenNo.join(",");
          let res = await confirmSubmit(user, rowPallenNoJoin, id);
          if (res.Status == 200) {
            toast("提交已完成");
            this.submitSure = true;
            this.rowPallenNo.length = 0;
            //给已确认加过去
            this.addData(this.rowData);
            //清空扫进的数据
            this.rowData = [];
            //再次获取
            this.PallentToBe = [];
            this.rowDataToBe = [];
            this.getInStorageInfo();
          } else {
            this.playMusic();
            toast(res.Msg);
            this.submitSure = false;
          }
        } else {
          this.playMusic();
          toast("数据为空");
        }
      } else {
        this.playMusic();
        toast("请先扫码");
      }
      this.$refs.pmfocus.focus();
    },
    //获取列表中的拍号
    findPalletNo() {
      console.log(this.submitSure);
      if (this.submitSure) {
        let _that = this;
        this.gridApi.forEachNode((node) => {
          _that.rowPallenNo.push(node.data.palletNo);
        });
      }
    },
    //点击未确认按钮
    toBeReceived() {
      if (this.buttoncolortobe == "info") {
        this.buttoncolortobe = "default";
      } else {
        this.buttoncolortobe = "info";
        this.buttoncolor = "default";
      }
      this.flag = "will";
      this.$refs.pmfocus.focus();
    },
    //点击已确认按钮
    haveReceived() {
      if (this.buttoncolor == "info") {
        this.buttoncolor = "default";
      } else {
        this.buttoncolor = "info";
        this.buttoncolortobe = "default";
      }
      this.flag = "had";
      this.$refs.pmfocus.focus();
    },
    //已确认遍历之后加数据
    addData(Data) {
      let _this = this;
      Data.map((item) => {
        _this.rowDataHad.push({
          materialCode: item.materialCode,
          palletNo: item.palletNo,
          palletName: item.palletName,
          prodDate: item.prodDate,
          quantity: item.quantity,
        });
      });
    },
    //待确认遍历之后减数据
    deleteData(val) {
      let numid = "";
      for (var i = 0; i < this.rowDataToBe.length; i++) {
        if (this.rowDataToBe[i].UniqueId == val) {
          numid = i;
        }
      }
      this.rowDataToBe.splice(numid, 1);
    },
    //待确认加数据
    async getInStorageInfo() {
      let res = await GetInStorageSure(
        this.$store.getters.WarehouseId,
        this.$store.getters.productionLine
      );
      if (res.Status == 200 && res.Data) {
        let _this = this;
        res.Data.map((item) => {
          //Num: this.adjustNumber(item.Num),
          _this.rowDataToBe.push({
            ProductId: item.ProductId,
            UniqueId: item.UniqueId,
            UniqueName: item.ProductName,
            ProductionDate: item.ProductionDate.substring(0, 9),
            Num: item.Num,
          });
        });
      } else {
        this.playMusic();
        toast(res.Msg);
      }
      console.log(res);
    },
    //获取待确认拍号
    getPallentToBe() {
      let _this = this;
      this.rowDataToBe.map((item) => {
        _this.PallentToBe.push(item.UniqueId);
      });
    },
    //获取刷新的待确认数据
    getInStorageSX() {
      this.PallentToBe = [];
      this.rowDataToBe = [];
      this.getInStorageInfo();
    },
    //依照拍号获取tobe页面的某个数据
    getAToBeData(val, res) {
      let numid = "";
      if (!this.rowData.find((it) => it.palletNo === res.palletNo)) {
        for (var i = 0; i < this.rowDataToBe.length; i++) {
          if (this.rowDataToBe[i].UniqueId == val) {
            numid = i;
          }
        }
        console.log(this.rowDataToBe);
        this.AToBeData = this.rowDataToBe[numid].UniqueName;
      }
    },
  },
  mounted() {
    this.gridApi = this.gridOptions.api;
    this.getInStorageInfo();
    this.$refs.pmfocus.focus();
  },
};
</script>
